package com.jungle.admin.handler;

import cn.dev33.satoken.exception.NotLoginException;
import com.jungle.common.constant.MessageConstant;
import com.jungle.common.core.domain.R;
import com.jungle.common.exception.BaseException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理器，处理项目中抛出的业务异常
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 捕获业务异常
     *
     * @param ex
     * @return
     */
    @ExceptionHandler
    public R<String> exceptionHandler(BaseException ex) {
        log.error("异常信息：{}", ex.getMessage());
        return R.fail(ex.getMessage());
    }

    @ExceptionHandler
    public R<String> notLoginExceptionHandler(NotLoginException e){
        log.info("登录异常：{}",e.getMessage());
        return R.fail(e.getMessage());
    }
    /**
     * 处理sql用户名重复异常，
     *
     * @param ex
     * @return
     */
    @ExceptionHandler
    public R<String> SqlExceptionHandler(SQLIntegrityConstraintViolationException ex) {
        String message = ex.getMessage();
        log.error("异常信息：{}", message);
        if (message.contains("Duplicate entry")) {
            return R.fail(message.split(" ")[2] + MessageConstant.ALREADY_EXIST);
        } else {
            return R.fail(MessageConstant.UNKNOWN_ERROR);
        }
    }
}
